package SeleniumPack;

import static org.testng.Assert.*;
import static org.testng.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class SeleniumBase {

	private static final int TIMEOUT = 30;
	protected WebDriver driver;
	protected String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();

	public SeleniumBase() {
		super();
	}

	@BeforeMethod
	public void setUp() throws Exception {
		driver = new HtmlUnitDriver();
		driver.manage().timeouts().implicitlyWait(TIMEOUT, TimeUnit.SECONDS);
	}

	protected void assertThatTheTitleIsCorrect(String title) {
		assertEquals(driver.getTitle(), title);
	}

	protected void assertThatTheTitleIsNotCorrect(String title) {
		assertNotEquals(driver.getTitle(), title);
	}

	protected void openUrl(String url) {
		driver.get(url + "/");
	}

	protected void assertThatElementExistsOnPage(By by) {
		driver.findElement(by);
	}

	protected void click(By by) {
		driver.findElement(by).click();
	}

	protected void insertText(By by, String text) {
		WebElement element = driver.findElement(by);
		element.clear();
		element.sendKeys(text);
	}

	@AfterMethod
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

}